<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import axios from 'axios'

const userStore = useUserStore()
const isHR = computed(() => userStore.isHR)

const loading = ref(false)
const departments = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogTitle = ref('添加部门')
const isEdit = ref(false)
const searchQuery = ref('')

const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
}

// 获取部门分页列表
const fetchDepartments = async () => {
  try {
    loading.value = true
    const response = await axios.get('/departments/page', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value || undefined
      }
    })
    const data = response.data || {}
    departments.value = Array.isArray(data.records) ? data.records : []
    total.value = typeof data.total === 'number' ? data.total : 0
    loading.value = false
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请重试')
    loading.value = false
  }
}

// 打开添加部门对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '添加部门'
  form.id = null
  form.name = ''
  form.description = ''
  dialogVisible.value = true
}

// 打开编辑部门对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑部门'
  form.id = row.id
  form.name = row.name
  form.description = row.description
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        if (isEdit.value) {
          // 编辑部门
          const response = await axios.put(`/departments/${form.id}`, form)
          ElMessage.success('部门更新成功')
        } else {
          // 添加部门
          const response = await axios.post('/departments', form)
          ElMessage.success('部门添加成功')
        }
        
        // 重新获取部门列表
        fetchDepartments()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交部门信息失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除部门 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/departments/${row.id}`)
      ElMessage.success('部门删除成功')
      // 重新获取部门列表
      fetchDepartments()
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 分页变化
const handlePageChange = (newPage) => {
  pageNum.value = newPage
  fetchDepartments()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  fetchDepartments()
}

// 搜索时重置页码并请求
watch(searchQuery, () => {
  pageNum.value = 1
  fetchDepartments()
})

onMounted(() => {
  fetchDepartments()
})
</script>

<template>
  <div class="department-container">
    <div class="page-header">
      <div class="page-title">部门管理</div>
      <div class="header-actions">
        <!-- 添加搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索部门名称或描述"
          clearable
          prefix-icon="el-icon-search"
          style="width: 250px; margin-right: 15px;"
        />
        <el-button 
          type="primary" 
          @click="openAddDialog" 
          v-if="isHR"
        >
          <el-icon><Plus /></el-icon>添加部门
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table 
        :data="departments" 
        border 
        style="width: 100%" 
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="部门名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" v-if="isHR">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin: 20px 0; text-align: right;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50, 100]"
      />
    </div>
    
    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        
        <el-form-item label="部门描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.department-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}
</style> 